package com.springboot.killingsystem.service;


import com.springboot.killingsystem.domain.OrderInfo;
import com.springboot.killingsystem.domain.SecondKillingOrder;
import com.springboot.killingsystem.domain.SecondKillingUser;
import com.springboot.killingsystem.redis.RedisService;
import com.springboot.killingsystem.redis.SecondKillingKey;
import com.springboot.killingsystem.util.Constant;
import com.springboot.killingsystem.util.MD5Util;
import com.springboot.killingsystem.util.UUIDUtil;
import com.springboot.killingsystem.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

@Service
public class SecondKillingService {
    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    RedisService redisService;

    private static final char[] ops = new char[] {'+', '-', '*'};

    @Transactional
    public OrderInfo secondKilling(SecondKillingUser user, GoodsVo goods) {

        // 减库存
        boolean success = goodsService.reduceStock(goods);
        if (success) {
            // 下订单并写入秒杀订单
            return orderService.createOrder(user, goods);
        }else {
            setGoodsOver(goods.getId());
        }
        return null;
    }

    /**
     * 获取秒杀结果
     */
    public long getSecondKillingResult(long userId, long goodsId) {
        SecondKillingOrder order = orderService.getSecondsKillingOrderByGoodsId(userId, goodsId);
        if (order != null) {
            return order.getOrderId();
        }

        boolean isOver = getGoodsOver(goodsId);
        if (isOver) {
            return Constant.ENDING;
        }

        return Constant.QUEUING;
    }

    /**
     * 库存为零时，在redis中添加标记
     */
    private void setGoodsOver(long goodsId) {
        redisService.set(SecondKillingKey.isGoodsOver, Constant.DEFAULT_KEY+goodsId, true);
    }

    /**
     * 判断零库存标记是否存在
     */
    private boolean getGoodsOver(long goodsId) {
        return redisService.exists(SecondKillingKey.isGoodsOver, Constant.DEFAULT_KEY+goodsId);
    }

    /**
     * 创建秒杀路径
     */
    public String createPath(SecondKillingUser user, long goodsId) {
        String str = MD5Util.md5(UUIDUtil.uuid() + Constant.PATH_RANDOM);
        redisService.set(
                SecondKillingKey.getSecondKillingPath,
                Constant.DEFAULT_KEY+user.getId()+Constant.SPLIT_SIGNAL+goodsId,
                str
        );
        return str;
    }

    /**
     * 验证秒杀路径
     */
    public boolean checkPath(SecondKillingUser user, long goodsId, String path) {
        String pathRedis = redisService.get(
                SecondKillingKey.getSecondKillingPath,
                Constant.DEFAULT_KEY + user.getId() + Constant.SPLIT_SIGNAL + goodsId,
                String.class
        );

        return path.equals(pathRedis);
    }

    /**
     * 创建图形验证码
     */
    public BufferedImage createVerifyCode(SecondKillingUser user, long goodsId) {
        if(user == null || goodsId <=0) {
            return null;
        }
        int width = 80;
        int height = 32;
        //create the image
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        // set the background color
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        // draw the border
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);
        // create a random instance to generate the codes
        Random rdm = new Random();
        // make some confusion
        for (int i = 0; i < 50; i++) {
            int x = rdm.nextInt(width);
            int y = rdm.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }
        // generate a random code
        String verifyCode = generateVerifyCode(rdm);
        g.setColor(new Color(0, 100, 0));
        g.setFont(new Font(Constant.FONT_CANDARA, Font.BOLD, 24));
        g.drawString(verifyCode, 8, 24);
        g.dispose();
        //把验证码存到redis中
        int rnd = calc(verifyCode);
        redisService.set(
                SecondKillingKey.getSecondKillingVerifyCode,
                Constant.DEFAULT_KEY + user.getId()+Constant.SPLIT_SIGNAL+goodsId,
                rnd
        );
        //输出图片
        return image;
    }

    /**
     * +-*算法的验证码
     */
    private String generateVerifyCode(Random rdm) {
        int num1 = rdm.nextInt(10);
        int num2 = rdm.nextInt(10);
        int num3 = rdm.nextInt(10);

        char op1 = ops[rdm.nextInt(3)];
        char op2 = ops[rdm.nextInt(3)];
        return ""+ num1 + op1 + num2 + op2 + num3;
    }

    private static int calc(String exp) {
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName(Constant.JAVASCRIPT);
            return (Integer) engine.eval(exp);
        }catch(Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 验证图形验证码
     */
    public boolean checkVerifyCode(SecondKillingUser user, long goodsId, int verifyCode) {
        if (goodsId <= 0) {
            return false;
        }
        Integer verifyCodeRedis = redisService.get(
                SecondKillingKey.getSecondKillingVerifyCode,
                Constant.DEFAULT_KEY + user.getId() + Constant.SPLIT_SIGNAL + goodsId,
                Integer.class
        );
        if (verifyCodeRedis == null || verifyCode - verifyCodeRedis != 0) {
            return false;
        }
        redisService.delete(
                SecondKillingKey.getSecondKillingVerifyCode,
                Constant.DEFAULT_KEY + user.getId() + Constant.SPLIT_SIGNAL + goodsId
        );
        return true;
    }
}
